package ltd.dujiabao.orderservice.dao;

import ltd.dujiabao.orderservice.domain.entity.OutboxMessage;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author Bowie Du
 * @date 2025/7/9 21:57
 */

@Repository
public interface OutboxMessageRepository extends CrudRepository<OutboxMessage, Long> {

    @Query(value = "select *  from `outbox_message` " +
            "where status = :status " +
            "limit :limit " +
            "for update skip locked", nativeQuery = true)
    List<OutboxMessage> findForUpdateSkipLocked(Byte status, Integer limit);

    @Modifying(clearAutomatically = true, flushAutomatically = true)
    @Transactional(rollbackFor = Exception.class)
    @Query(value = "update OutboxMessage set status = :status, errorMsg = :errorMsg, updatedAt = :updateAt " +
            " where messageId = :messageId")
    int updateStatusAndErrorMsgByMessageId(String messageId, Byte status, String errorMsg, LocalDateTime updateAt);

    int countByStatus(Byte status);
}
